<template>
	<div class="submit-code-wrap">
		<h3>{{ $t('code.submit') }}</h3>

		<br>

		<div class="mb-3 lang-wrap">
			<select class="form-select" v-model="lang">
				<option v-for="item in languages" :key="item.id" :value="item.id">
					{{ item.lang }} ({{ item.compile }} {{ item.version }})
				</option>
			</select>
		</div>

		<div class="mb-3 code-wrap">
			<textarea class="form-control code" rows="20" cols="100" v-model="code"
					placeholder="Please input your source code."></textarea>
		</div>

		<div class="func-btn-group">
			<button class="btn btn-success" @click="submitCode">
				{{ $t('submit') }}
			</button>


			<span class="solution-result">
				<span v-if="message">{{ message }}</span>

				<span :class="mapping.class" v-if="mapping">
					{{ $t('result.' + mapping.name) }}
				</span>

				<template v-if="runId">
					<span class="details">
						<span>{{ $t('runId') }}: </span>

						<a :href="'/solution/' + runId" target="_blank">
							{{ runId }}
						</a>
					</span>

					<a class="close" @click="close">✖</a>
				</template>
			</span>
		</div>
	</div>
</template>


<script type="module">
	import { StatusService, ConfigService } from '@/common/common.object';

	export default {
		name: 'submit-code',
		props: ['submit', 'runId', 'message', 'close'],
		data() {
			return {
				lang: "0",
				languages: null,
				code: '#include <stdio.h>\n\nint main() {\n	printf("Hello World!\\n");\n	return 0;\n}',

				mapping: null,
				disableSubmit: false,
			};
		},
		created() {
			ConfigService.getLanguages().then(result => {
				this.languages = Object.freeze(result);
			});
		},
		watch: {
			runId(newValue, oldValue) {
				if (!newValue) return;

				this.disableSubmit = true;
				this.mapping = StatusService.resultMapping[0];
				console.log('[judge] runId: ', newValue);

				const tryTimes = 32;
				const interval = 1000;
				let counter = 0;

				const temp = setInterval(() => {
					counter++;

					StatusService.get(newValue).then(result => {
						if (true === result.complete) {
							clearInterval(temp);

							this.disableSubmit = false;
						}

						this.mapping = StatusService.resultMapping[result.status];
					}).catch(error => {
						console.log('error: ', error);
					});


					if (counter > tryTimes) {
						clearInterval(temp);

						this.disableSubmit = false;
					}
				}, interval);
			}
		},
		methods: {
			submitCode() {
				if (!this.disableSubmit) {
					this.submit(this.lang, this.code);
				}
			},
		}
	}
</script>


<style scoped>
	.code {
		width: 100%;
	}

	.solution-result {
		padding: 16px;
	}

	.details {
		padding-left: 16px;
	}

	.close {
		padding-left: 8px;
		cursor: pointer;

		color: red;
	}
</style>
